package com.ry.demo.register.server;

import com.ry.demo.register.server.dto.HeartbeatRequest;
import com.ry.demo.register.server.dto.HeartbeatResponse;
import com.ry.demo.register.server.dto.RegisterRequest;
import com.ry.demo.register.server.dto.RegisterResponse;

/**
 * @Author: lihui
 * @Date: 2021-12-01 11:35
 * @Description:
 */
public class RegisterServerController {

    private static Registry registry =  Registry.getInstance();

    /**
     * 服务注册
     * @param registerRequest
     * @return
     */
    public RegisterResponse addInstance(RegisterRequest registerRequest){
        RegisterResponse registerResponse = new RegisterResponse();

        try {

            ServiceInstance serviceInstance = new ServiceInstance();
            serviceInstance.setServiceName(registerRequest.getServiceName());
            serviceInstance.setHostname(registerRequest.getHostname());
            serviceInstance.setServiceInstanceId(registerRequest.getServiceInstanceId());
            serviceInstance.setIp(registerRequest.getIp());
            serviceInstance.setPort(registerRequest.getPort());

            registry.addInstance(serviceInstance);

            registerResponse.setStatus(RegisterResponse.SUCCESS);
        } catch (Exception e){
            e.printStackTrace();
            registerResponse.setStatus(RegisterResponse.FAILURE);
        }

        return registerResponse;
    }


    /**
     * 服务续约
     * @return
     */
    public HeartbeatResponse renew(HeartbeatRequest heartbeatRequest){
        HeartbeatResponse heartbeatResponse = new HeartbeatResponse();

        ServiceInstance serviceInstance = registry.getServiceInstance(
                heartbeatRequest.getServiceName(),
                heartbeatRequest.getServiceInstanceId());
        if (serviceInstance==null){
            System.out.println("服务实例已经下线了【"+heartbeatRequest.getServiceName()+"】");
            heartbeatResponse.setStatus(HeartbeatResponse.FAILURE);
        }else {
            serviceInstance.renew();
        }

        return heartbeatResponse;
    }

}
